/***********************String Operation**************************/
String.prototype.Trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.replaceAll = function(findText, replaceText) {
    var regExp = new RegExp(findText, "g");
    return this.replace(regExp, replaceText);
};
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
};
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
Array.prototype.removeByIndex = function(index) {
    this.splice(index, 1);
};
Date.prototype.Format = function(fmt)
{ //author: meizz
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
/***********************Tools**************************/
var tool = {
    isIE: function() {
        if (!!window.ActiveXObject || "ActiveXObject" in window) {
            return true;
        } else {
            return false;
        }
    },
    checkEmail: function(email) {
        var emailreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
		return emailreg.test(email);
    },
    getLength: function(str) {//处理输入的内容是文字还是字母的函数
        return String(str).replace(/[^\x00-\xff]/g,'aa').length;
    },
    formatTimeToSeconds: function(str) {//将类似于2:02:30的字符串转化成秒
        var arr = str.split(':');
        var length = arr.length;
        if (length == 1) {
            return parseInt(arr[0]);
        } else if (length == 2) {
            return parseInt(arr[0])*60 + parseInt(arr[1]);
        } else if (length == 3) {
            return parseInt(arr[0])*60*60 + parseInt(arr[1])*60 + parseInt(arr[2]);
        }
    },
    formatTimeToString: function(seconds){ //将秒转化为类似于2:30的字符串
        var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60):Math.floor(seconds/60);
        var s =Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60));
        return m+":"+s;
    },
    cookie: function(name, value, options) {
       name = encodeURIComponent(name);
       if (typeof value != 'undefined') {
           options = options || {};
           if (value === null) {
               value = '';
               options.expires = -1;   // invalidate it
           }
           var expires = '',
           path = options.path ? '; path=' + options.path : '',
           domain = options.domain ? '; domain=' + options.domain : '',
           secure = options.secure ? '; secure' : '';
           if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
               if(typeof options.expires === 'number') {
                   var date = new Date();
                   date.setTime(date.getTime() + (options.expires * 86400000));    //24 * 60 * 60 * 1000 microseconds
               } else {
                   var date = options.expires;
               }
               expires = '; expires=' + date.toUTCString(); //use expires attribute, max-age is not supported by IE
           }
           document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
       } else {
           var cookieValue = null;
           if (document.cookie) {
               var cookies = document.cookie.split(';');
               for (var i = 0, j = cookies.length; i < j; i++) {
                   var cookie = cookies[i].replace(/^\s+|\s+$/g, '');
                   // Does this cookie string begin with the name we want?
                   if (cookie.substring(0, name.length + 1) === (name + '=')) {
                       cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                       break;
                   }
                   if (cookie === name) {
                       cookieValue = "";
                       break;
                   }
               }
           }
           return cookieValue;
       }
    },
    //允许调用方通过resVar传递ajax返回的变量名, 避免同时多个ajax请求返回变量名相同时造成的混乱
    //sync_flag: true, 表示同步发起请求
    //cache_flag: true, 以url为key, 对返回的结果做内存缓存, 多次请求时从缓存返回
    cache: {},
	ajaxGet: function(url, resVar, successCallBack, errorCallBack, sync_flag, cache_flag) {
        var async = true;
        //退出登录接口, 或者指定同步的, 采用同步请求
        if (url.indexOf('logout') != -1 || sync_flag === true) {
            async = false;
        }
        //对于ie指定编码格式
        if (tool.isIE()) {
            url += '&is_gbk=1';
        }

        if (typeof cache_flag == 'undefined') {
            cache_flag = false;
        }
        //设置使用缓存, 先从缓存中取
        if (cache_flag == true) {
            var url_key = hex_md5(url);
            if (typeof tool.cache[url_key] != 'undefined') {
                successCallBack(tool.cache[url_key]);
                return;
            }
        }

		$.ajax({
            type: "GET",
            url: url,
            dataType: 'script',
            async: async,
            success: function(){
				var res = eval(resVar);
                //设置使用缓存, 将数据填入缓存
                if (cache_flag == true) {
                    var url_key = hex_md5(url);
                    tool.cache[url_key] = res;
                }
				successCallBack(res);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
//				alert(errorThrown);
			}
		});
	},
    //允许调用方通过resVar传递ajax返回的变量名, 避免同时多个ajax请求返回变量名相同时造成的混乱
	ajaxPost: function(url, resVar, params, successCallBack, errorCallBack) {
		$.ajax({
            type: "POST",
            url: url,
            data: params,
            dataType: 'script',
            success: function(){
				var res = eval(resVar);
				successCallBack(res);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
//				alert(errorThrown);
			}
		});
	},
    //异步加载页面片
    ajaxFragment: function(url, successCallBack) {
        if (tool.isIE()) {
            url += '&is_gbk=1';
        }
        $.get(url, function(content){
            successCallBack(content);
        });
    },
    refreshSelectContainer: function(obj) {
        obj.children('option').eq(0).attr('selected', true);
        obj.val('0');
        obj.children('option:gt(0)').remove();
    },
    getUrlParams: function(url) {
        if (typeof url == 'undefined') {
            url = location.href;
        }
        var params = {};
        if (url.indexOf("?") != -1) {
            var pts = url.split("?");
            var str = pts[1];
            strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                var parts = strs[i].split('=');
                if (parts.length >= 2) {
                    params[parts[0]] = parts[1];
                }
            }
        }
        return params;
    },
    getUrlHost: function(url) {
        var host = null;
        if(typeof url == "undefined" || null == url)
            url = window.location.href;
        var regex = /.*\:\/\/([^\/]*).*/;
        var match = url.match(regex);
        if(typeof match != "undefined" && null != match) {
            host = 'http://' + match[1];
        }
        return host;
    },
    htmlspecialchars_decode: function(str){
        str = str.toString().replace(/&amp;/g, '&');
        str = str.toString().replace(/&lt;/g, '<');
        str = str.toString().replace(/&gt;/g, '>');
        str = str.toString().replace(/&quot;/g, "'");
        str = str.toString().replace(/&#039;/g, "'");
        return str;
    },
    get_loading_status_html: function() {
        return '<li id="loadingbox" style="height:200px; width:100%;"><a class="loadingstatus" style="display:block; height:100px; min-height: 100px"></a><p style="text-align:center;font-size:12px;line-height:30px; color:#333;">正在加载中请稍后…</p></li>';
    },
    /**
     * 对象转查询字符串
     */
    objToQueryString: function(obj) {
        if (null === obj || typeof obj != 'object') {
            return '';
        }
        var ans = '';
        for (k in obj) {
            if (obj.hasOwnProperty(k)) {
                if (ans.length > 0) {
                    ans += '&';
                }
                ans += k + '=' + obj[k];
            }
        }
        return ans;
    },
    /**
     * 查询字符串转对象
     */
    queryStringToObject: function(qs) {
        var items = qs.split('&');
        var ans = {};
        for (var i = 0; i < items.length; i++) {
            var kv = items[i].split('=');
            if (kv.length < 2) {
                continue;
            }
            ans[kv[0]] = kv[1];
        }
        return ans;
    },
    /**
     * 将秒转换成时间间隔
     * @param seconds 秒
     * @param show_zero 是否显示0值字段, 默认为false
     * @param mod 显示模式 默认为自动模式, 月按30天算, 年按365天算
     *      默认为 0x15(xx天xx时xx分xx秒)
     *      0x1 秒 0x2 分 0x4 时 0x8 天 0x16 周 0x 32月 0x64 显示年 通过与运算组合
     * @return x年x天x时x秒, 失败返回false
     */
    parseTimeInterval: function(seconds, show_zero, mod) {
        if (isNaN(seconds)) {
            return false;
        }
        //转成整数
        seconds = parseInt(seconds);
        var time_fileds = [
            {mod: 0x64, name:'年', interval: 60 * 60 * 24 * 365},
            {mod: 0x32, name:'月', interval: 60 * 60 * 24 * 30},
            {mod: 0x16, name:'周', interval: 60 * 60 * 24 * 7},
            {mod: 0x8 , name:'天', interval: 60 * 60 * 24, fill: 2},//不足2位 则填充为2位
            {mod: 0x4 , name:'时', interval: 60 * 60, fill: 2},
            {mod: 0x2 , name:'分', interval: 60, fill: 2},
            {mod: 0x1 , name:'秒', interval: 1, fill: 2},
        ];
        var left = seconds, ans = '';
        if (!mod) {
            mod = 0x1 | 0x2 | 0x4 | 0x8;
        }
        for (var i = 0; i < time_fileds.length; i++) {
            var e = time_fileds[i];
            //模式过滤
            if (mod & e.mod) {
                var num = Math.floor(left/e.interval);
                var str = '';
                //加入到结果
                if (num > 0 || show_zero) {
                    str = num + e.name;
                    //填充0
                    if (num < 10 && e.fill > 1) {
                        var t = e.fill;
                        while(--t) {
                            str = '0' + str;
                        }
                    }
                }
                ans += str;
                //更新剩余秒数
                left -= num * e.interval;
            }
        }
        return ans;
    }

}

//监听事件
function addEventHandler(target,type,func){
    if(target.addEventListener){
        //监听IE9，谷歌和火狐
        target.addEventListener(type,func,false);
    }else if(target.attachEvent){
        target.attachEvent("on" + type, func);
    }else{
        target["on" + type] = func;
    }
}
/*
 * removeEventHandler:移除Dom元素的事件
 *
 *  target：监听对象
 *  type：监听函数类型
 *  func：监听函数
 */
function removeEventHandler(target, type, func) {
    if (target.removeEventListener){
        //监听IE9，谷歌和火狐
        target.removeEventListener(type, func, false);
    } else if (target.detachEvent){
        target.detachEvent("on" + type, func);
    }else {
        delete target["on" + type];
    }
}

$(document).ready(function(){

    detectBrowser();

})

function detectBrowser(){
    var b_agent = navigator.userAgent.toLowerCase();

    var browser_name = !-[1,]?'ie':(b_agent.indexOf("firefox")>0) ? 'firefox' : (b_agent.indexOf("chrome")>0) ? 'chrome': window.opera ? 'opera': window.openDatabase ? 'safari': 'unkonw';
    var b_version = (browser_name=='ie') ? b_agent.match(/msie ([\d.]+)/)[1]:(browser_name=='firefox') ? b_agent.match(/firefox\/([\d.]+)/)[1] : (browser_name=='chrome') ? b_agent.match(/chrome\/([\d.]+)/)[1] : (browser_name=='opera') ? b_agent.match(/opera.([\d.]+)/)[1] : (browser_name=='safari') ?b_agent.match(/version\/([\d.]+)/)[1] : '0';
    var version = parseInt(b_version);

    if(browser_name == 'ie'){
        if(version < 9){
            var clientHtml = '<div id="brower_client_cover">' +
	 						'<div id="brower_box">'+
								'<div id="brower_header">'+
									'<span>浏览器使用提示</span>'+
									'<a id="close_brower"></a>'+
								'</div>'+
								'<div id="browser_title" class="clearfix">'+
									'<p></p>'+
								'</div>'+
								'<div id="browser_360" class="clearfix">'+
									'<p id="titleccc">若您使用360浏览器请要使用极速模式</p>'+
									'<div class="clearfix down_s">'+
										'<img src="/apps/common/images/internet/360q.png"/>'+
									'</div>'+
								'</div>'+
								'<div id="browser_down" class="clearfix">'+
									'<p id="titleccc">若使用其他浏览器建议使用以下浏览器</p>'+
									'<div class="clearfix down_eb"><p class="down_title">火狐浏览器</p><div class="left"><img src="/apps/common/images/internet/huoh.png"/><a class="down_e">去下载浏览器</a></div></div>'+
									'<div class="clearfix down_eb"><p class="down_title">360浏览器</p><div class="left"><img src="/apps/common/images/internet/360j.png"/><a class="down_e">去下载浏览器</a></div><div class="left"><img src="/apps/common/images/internet/360s.png"/><a class="down_e">去下载浏览器</a></div></div>'+
									'<div class="clearfix down_eb"><p class="down_title">ie浏览器（最好使用最高版本）<a href="http://zhidao.baidu.com/link?url=D_wX-0g2QPOXF-pwtMG6USffd1MxtCC27V0eFfNgfX8T6S4ey_thcjJoJHI2wBIywMNpH18EkMOOmLGnLRM_gOuBCspnmo8ymg42_LKqbYW">xp系统怎样升级ie浏览器点击了解详情</a></p><div class="left"><img src="/apps/common/images/internet/ie9.jpg"/><a class="down_e">去下载浏览器</a></div><div class="left"><img src="/apps/common/images/internet/ie10.png"/><a class="down_e">去下载浏览器</a></div><div class="left"><img src="/apps/common/images/internet/ie11.png"/><a class="down_e">去下载浏览器</a></div></div>'+
								'</div>'+
							'</div>'+
						'</div>';

            $('body').append(clientHtml);
            $('#browser_title p').text('您好！您使用的'+browser_name+b_version+'版本太低易导致一些功能显示可能不是太好，为了您更好的使用平台功能，请看以下提示');
            $(document).on('click','#close_brower',function(){
                $('#brower_client_cover').fadeOut(100);
            })
        }
    }
}
function flashChecker(){
    var hasFlash=0;　　　　//是否安装了flash
    var flashVersion=0;　　//flash版本

    if(document.all)
    {
        var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        if(swf) {
            hasFlash=1;
            VSwf=swf.GetVariable("$version");
            flashVersion=parseInt(VSwf.split(" ")[1].split(",")[0]);
        }
    }else{
        if (navigator.plugins && navigator.plugins.length > 0)
        {
            var swf=navigator.plugins["Shockwave Flash"];
            if (swf)
            {
                hasFlash=1;
                var words = swf.description.split(" ");
                for (var i = 0; i < words.length; ++i)
                {
                    if (isNaN(parseInt(words[i]))) continue;
                    flashVersion = parseInt(words[i]);
                }
            }
        }
    }
    return {f:hasFlash,v:flashVersion};
}
function checkhHtml5() {
	  if (window.applicationCache) {
      	return true;
      } else {
      	return false;
 	  }
}


//通用函数
var getId = function( id ) {
    return document.getElementById(id);
}

var getClass = function( oParent, sClass ) {
    var aEle = getId(oParent).getElementsByTagName('*');
    var aResult = [];
    var re = new RegExp('\\b'+sClass+'\\b','i');
    var i = 0;
    for(i = 0;i < aEle.length;i++) {
        if(re.test(aEle[i].className)){
            aResult.push(aEle[i]);
        }
    }
    return aResult;
}

var get_tpl = function( id ) {
    return getId('tpl_' + id).innerHTML;
}

var getBodyW = function() {
    return document.body.offsetWidth;
}

var getBodyH = function() {
    return document.body.offsetHeight;
}

var getElTop = function( ele ) {
    return ele.offsetTop + 260;
}

// 创建班级弹框遮罩层
function showCover() {
    var ccCoverTpl = "<div class='ccCover'></div>";
    $('body').append(ccCoverTpl);
    var $cover = $('.ccCover');
    var w = $(document).width();
    var h = $(document).height();
    $cover.width(w);
    $cover.height(h);
    $(window).resize(function(){
        var w = $(document).width();
        var h = $(document).height();
        $cover.width(w);
        $cover.height(h);
    })
}

function removeCover() {
    var $cover = $('.ccCover');
    if($cover) {
        $cover.remove();
    }
}

/* tabs */
function tabSlider(obj, count) {
    var _this = this;
        _this.obj = obj;
        _this.count = count;
        _this.time = 2000;
        _this.n = 0;
    var t;
    this.slider = function(){
        $(_this.obj + " .tabnav li").on("click",function(){
            $(this).addClass("on").removeClass("uon").siblings().removeClass("on").addClass('uon');
            var index = $(_this.obj + ' .tabnav li').index(this);
			if(index == 0){
				$(this).find('.t_text').text('我的消息');
				$(this).siblings('li').find('.t_text').text('');
				$('.creatClassBox').find('.close').click();
			}else{
				$(this).find('.t_text').text('我的班级');
				$(this).siblings('li').find('.t_text').text('');
			}
            $(_this.obj + ' .tabContent .content').eq(index).show().siblings().hide();
            _this.n = index;
        })
    }

    this.addhover = function(){
        _this.n = _this.n >= (_this.count - 1) ? 0 : ++_this.n;
        $(_this.obj + ".tabnav li").eq(_this.n).trigger("click");
    }

    this.factory = function(){
        this.slider();
        this.addhover();
    }

    this.factory();
}

/*
* popDialog
 */
function DialogHelper(title, dialogDiv, w, h) {
    var title = title;
    // 设置消息正文
    var content = "";
    // 设置按钮
    /*var buttons = {
        '确定' : function() {
            $(this).dialog('close');
        }
    };*/
    var width = w;
    var height = h;
    var modal = false;
    var dialogDiv = dialogDiv;
    // getter & setter
    var setTitle = function(val) {
        title = val;
    }
    var getTitle = function() {
        return title;
    }
    var setContent = function(val) {
        content = val;
    }
    var getContent = function() {
        return content;
    }
    var setButtons = function(val) {
        buttons = val;
    }
    var getButtons = function() {
        return buttons;
    }
    var setWidth = function(val) {
        width = val;
    }
    var getWidth = function() {
        return width;
    }
    var setHeight = function(val) {
        height = val;
    }
    var getHeight = function() {
        return height;
    }
    var setModal = function(val) {
        modal = val;
    }
    var getModal = function() {
        return modal;
    }
    var setDialogDiv = function(val) {
        dialogDiv = val;
    }
    var getDialogDiv = function() {
        return dialogDiv;
    }
    // open方法，弹出对话框
    var open = function() {
        if (arguments.length == 1 && (typeof arguments[0] == "string"))
            setContent(arguments[0]);
        if (arguments.length == 2 && (typeof arguments[0] == "string")
                && (typeof arguments[1] == "string")) {
            setTitle(arguments[0]);
            setContent(arguments[1]);
        }
        // 这个克隆很重要,否则反复添加正文
        /*var dlg = dialogDiv.clone();
        dlg.children().filter("p").html(
                dialogDiv.children().filter("p").html()
                        + getContent());*/
        dialogDiv.dialog({
            //autoOpen: true,
            //show : 'scale',
            //hide : 'scale',
            position : 'center',
            height : getHeight(),
            width : getWidth(),
            modal : getModal(),
            title : getTitle(),
            //buttons : getButtons(),
            modal: true,
            close: function(ev, ui) {
                //console.log($('.ui-dialog').html());
                $('.ui-dialog').remove();
            }
        });
    }
    // 对外界暴露一些公共方法
    return {
        setTitle : setTitle,
        setContent : setContent,
        setButtons : setButtons,
        setWidth : setWidth,
        setHeight : setHeight,
        setModal : setModal,
        setDialogDiv : setDialogDiv,
        open : open
    }
}

//数字变中文
function numberToChinese(num) { 
    if (!/^\d*(\.\d*)?$/.test(num)) { alert("Number is wrong!"); return "Number is wrong!"; } 
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九"); 
    var BB = new Array("", "十", "百", "千", "万", "亿", "点", ""); 
    var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; 
    for (var i = a[0].length - 1; i >= 0; i--) { 
        switch (k) { 
            case 0: re = BB[7] + re; break; 
            case 4: if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0])) 
                        re = BB[4] + re; break; 
            case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break; 
        } 
        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re; 
        if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++; 
    } 
    if (a.length > 1) //加上小数部分(如果有小数部分) 
    { 
        re += BB[6]; 
        for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)]; 
    } 
    if(num == '10'){
        re = '十';
    }
    return re; 
}
//得到事件
function getEvent () {
    if(window.event)    {return window.event;}
    func=getEvent.caller;
    while(func!=null){
        var arg0=func.arguments[0];
        if(arg0){
            if((arg0.constructor==Event || arg0.constructor ==MouseEvent
                        || arg0.constructor==KeyboardEvent)
                    ||(typeof(arg0)=="object" && arg0.preventDefault
                        && arg0.stopPropagation)){
                return arg0;
            }
        }
        func=func.caller;
    }
    return null;
}
//阻止冒泡
function cancelBubble () {
    var e=getEvent();
    if(window.event){
        //e.returnValue=false;//阻止自身行为
        e.cancelBubble=true;//阻止冒泡
    }else if(e.preventDefault){
        //e.preventDefault();//阻止自身行为
        e.stopPropagation();//阻止冒泡
    }
}
